// src/services/wechatAuth.ts
import axios from 'axios';
import qs from 'qs';

// 微信登录配置
const WECHAT_CONFIG = {
  appId: 'YOUR_WECHAT_APP_ID', // 微信开放平台应用ID
  appSecret: 'YOUR_WECHAT_APP_SECRET', // 微信开放平台应用密钥
  redirectUri: 'https://yourdomain.com/auth/wechat/callback', // 授权回调地址
  scope: 'snsapi_userinfo', // 授权作用域
  state: 'wechat_auth', // 自定义状态参数
};

// 后端API地址
const API_BASE_URL = 'https://your-api-domain.com';

export const WechatAuth = {
  // 获取微信登录URL
  getLoginUrl: async (): Promise<string> => {
    try {
      const response = await axios.get(`${API_BASE_URL}/auth/wechat/url`);
      return response.data.url;
    } catch (error) {
      console.error('获取微信登录URL失败:', error);
      throw error;
    }
  },

  // 处理微信回调
  handleCallback: async (code: string, state: string): Promise<any> => {
    try {
      const response = await axios.post(`${API_BASE_URL}/auth/wechat/callback`, {
        code,
        state,
      });
      return response.data;
    } catch (error) {
      console.error('处理微信回调失败:', error);
      throw error;
    }
  },

  // 获取用户信息
  getUserInfo: async (accessToken: string): Promise<any> => {
    try {
      const response = await axios.get(`${API_BASE_URL}/auth/wechat/userinfo`, {
        headers: {
          Authorization: `Bearer ${accessToken}`,
        },
      });
      return response.data;
    } catch (error) {
      console.error('获取用户信息失败:', error);
      throw error;
    }
  },
};